﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;

namespace Perceiveit.Xml
{
    internal class XPropertyText<T> : XPropertySimple<T>
    {
        
        public override T GetValue(XEntity entity)
        {
            T value;
            XPropertyCell<T> tcell;
            XElement node;

            if (!this.TryGetCell(entity, out tcell))
            {
                node = this.GetXElement(entity, false);
                if (node == null)
                {
                    value = default(T);
                }
                else
                {
                    string sval = node.Value;
                    value = this.Converter.FromString(sval);
                    tcell = this.RegisterNewCell(entity, node, value);
                }
            }
            else if (this.Volatile)
            {
                node =  tcell.Node as XElement;
                value = this.Converter.FromString(node.Value);
            }
            else
                value = tcell.Value;

            return value;
        }

        public override void SetValue(XEntity entity, T value)
        {
            string sval = this.Converter.ToString(value);

            XElement ele;
            XPropertyCell<T> tcell;

            if (this.TryGetCell(entity, out tcell))
            {
                ele = tcell.Node as XElement;
                ele.Value = sval;
                tcell.Value = value;
            }
            else
            {
                ele = this.GetXElement(entity, true);
                ele.Value = sval;
                tcell = this.RegisterNewCell(entity, ele, value);
            }
        }

        public override void ClearValue(XEntity entity)
        {
            XElement ele = this.GetXElement(entity, false);
            if (null != ele)
            {
                ele.Value = string.Empty;
            }
            entity.ClearCell(this);
        }

        
    }
}
